#include "Object3D.h"

#include <stdio.h>
#include <string.h>
#include <GL/glut.h>

CObject3D::CObject3D(char *fname)
{
	memset(&header, 0, sizeof(header));

	FILE *f = fopen(fname,"rb");

	if (!f)
		return;

	fread(&header, sizeof(header), 1, f);

	if (header.signature == 0x4F424433)
	{
		m_verts = new TPoint3D[header.nrVert];
		m_tverts = new TPoint2D[header.nrTVert];
		m_faces = new TFace[header.nrFaces];

		fread(m_verts, header.nrVert * sizeof(TPoint3D), 1, f);
		fread(m_tverts, header.nrTVert * sizeof(TPoint2D), 1, f);
		fread(m_faces, header.nrFaces * sizeof(TFace), 1, f);
	}

	fclose(f);
}

void CObject3D::render()
{
	glPushMatrix();
	glScalef(0.1f, 0.1f, 0.1f);
	glBegin(GL_TRIANGLES);
	for (int i=0;i<header.nrFaces;i++)
	{
		for (int j=0;j<3;j++)
		{
			glNormal3f(m_faces[i].normal[j].x, m_faces[i].normal[j].y, m_faces[i].normal[j].z);
			glTexCoord2d(m_tverts[m_faces[i].tvert[j]].x, m_tverts[m_faces[i].tvert[j]].y);
			glVertex3f(m_verts[m_faces[i].vert[j]].x, m_verts[m_faces[i].vert[j]].y, m_verts[m_faces[i].vert[j]].z);
		}
	}

	glEnd();
	glPopMatrix();
}